<template>
	<view>
		<uni-popup ref="process" :is-mask-click="false" type="center">
			<view class="popup-view">
				<view class="popup-content">
					<progress :percent="progress" stroke-width="8" active-color="#5b95ff" style="overflow: hidden;border-radius: 6px"></progress>
				</view>
				<view style="text-align: center;color: #5b95ff;padding: 10px;">
					{{ '下载中: ' +  progress + '%'}}
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { store } from '@/api/service/store-service.js'
import { loger } from '@daelui/dogjs/dist/components'
const gapTime = 0 // 24 * 60 * 60 * 1000

export default {
	props: {
		message: {
			type: String,
			default: '是否下载更新？'
		}
	},

	data() {
		return {
			progress: 0
		}
	},

	methods: {
		// 下载资源
    download (url) {
			return new Promise((resolve) => {
				// 下载并安装
				let downloadTask = uni.downloadFile({
					url: url,
					success: (downloadResult) => {
						if (downloadResult.statusCode === 200) {
							plus.runtime.install(downloadResult.tempFilePath, {
								force: false
							}, function() {
								resolve(true)
								plus.runtime.restart()
							}, function(e) {
								console.log(4444)
								resolve(false)
								loger.error('Install fail...')
							})
						}
					},
					complete: () => {
						this.$refs.process.close()
						this.progress = 0
						this.$emit('complete')
					}
				})
				downloadTask.onProgressUpdate(res => {
					this.$refs.process.open()
					this.progress = res.progress
				})
				// 仅下载
				// plus.runtime.openURL(url)
			})
		},
		// 获取下载地址
		getDownloadUrl (data) {
			let version = data?.version
			let downloadFilename = 'yhxfz-' + version + '.apk'
			let url = this.vuex_config.baseUrl + '/common/files/download?resource='
				+ encodeURIComponent(data.downloadUrl)
				+ '&downloadFilename=' + downloadFilename
			return url
		}
	}
}

// 确认是否下载
export const confirmUpgrade = function ({ message } = {}) {
	return new Promise((resolve) => {
		uni.showModal({
			title: '提示',
			content: message || '是否下载更新？',
			showCancel: true,
			success: (res2) => {
				if (res2.confirm) {
					resolve(true)
				} else {
					resolve(false)
				}
				store.getItem('upgrade-time', Date.now())
			}
		})
	})
}

// 是否可升级
export const isUpgradeAble = async (gap) => {
	gap = gap || gapTime
	let time = await store.getItem('upgrade-time')
	// 点击取消时间小于1天，则不提示
	if (time && time > Date.now() - gap) {
		return false
	}
	return true
}
</script>

<style>
.popup-view {
	padding: 40px 20px 20px;
	width: 60vw;
	background: #fff;
	border-radius: 10px;
}
</style>
